package com.hidquat;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;

/**
 * surface viewer for STL object
 */

public class STLView extends GLSurfaceView {

    private STLRenderer stlRenderer;
    private float q0;
    private float q1;
    private float q2;
    private float q3;

    private float angle_last = 0;
    private float angle_pass = 0;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                q0 = msg.getData().getFloat("q0");
                q1 = msg.getData().getFloat("q1");
                q2 = msg.getData().getFloat("q2");
                q3 = msg.getData().getFloat("q3");
                double halfDelta = Math.acos(q0);
                float angle = (float)Math.toDegrees(halfDelta*2);
                float sinHalfDelta = (float)Math.sqrt(1-q0*q0);

                if(Math.abs(angle_pass - angle) > 2){
                    angle_pass = angle;
                }else if(Math.abs(angle_last - angle) > 0.5) {
                    angle_pass = 0.5f*angle_pass + 0.5f*angle;
                }
                angle_last = angle;

                stlRenderer.setRotation(angle_pass, -q1/sinHalfDelta, -q2/sinHalfDelta, q3/sinHalfDelta);
                requestRender();
            }
        };
    };

    public STLView(Context context, STLObject stlObject) {
        super(context);

        stlRenderer = new STLRenderer(stlObject);
        setRenderer(stlRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        //setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    public Handler getHandler() {
        return handler;
    }
    public void delete (){
        stlRenderer.delete();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
